<template>
  <div class="notes-container">
    <div class="notes-header">
      <div class="title">笔记</div>
      <el-button
        type="primary"
        class="create-note-btn"
        @click="createNewNote">
        新建笔记
      </el-button>
    </div>

    <div class="search-container">
      <div class="search-input-group">
        <el-input
          v-model="userIdSearch"
          placeholder="输入用户ID查看"
          class="search-input"
          clearable>
          <template #prefix>
            <el-icon><User /></el-icon>
          </template>
        </el-input>
        <el-button
          type="primary"
          @click="handleUserSearch"
          :icon="Search"
          class="search-button">
          查询
        </el-button>
      </div>

      <el-autocomplete
        v-model="topicSearch"
        :fetch-suggestions="queryTopicSuggestions"
        placeholder="搜索话题"
        @select="handleTopicSelect"
        class="search-input"
        clearable>
        <template #prefix>
          <el-icon><Collection /></el-icon>
        </template>
      </el-autocomplete>
    </div>

    <el-table
      :data="filteredNotes"
      style="width: 100%"
      @row-click="viewNoteDetails">
      <el-table-column prop="title" label="标题" min-width="150">
        <template #default="scope">
          {{ scope.row.content || '无标题' }}
        </template>
      </el-table-column>
      <el-table-column prop="topic" label="话题" min-width="120"/>
      <el-table-column prop="is_public" label="状态" width="80">
        <template #default="scope">
          <el-tag :type="scope.row.is_public ? 'success' : 'info'">
            {{ scope.row.is_public ? '公开' : '私密' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="created_at" label="创建时间" min-width="120">
        <template #default="scope">
          {{ formatDate(scope.row.created_at) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="120" fixed="right">
        <template #default="scope">
          <div class="action-buttons">
            <el-button
              v-if="scope.row.user === currentUserId"
              type="text"
              size="small"
              @click.stop="editNote(scope.row)"
              class="edit-btn"
            >
              编辑
            </el-button>
            <el-button
              v-if="scope.row.user === currentUserId"
              type="text"
              size="small"
              class="delete-btn"
              @click.stop="deleteNote(scope.row)"
            >
              删除
            </el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <NoteEditor
      v-if="showNoteEditor"
      :note-id="currentNoteId"
      :user-info="userInfo"
      @close="handleEditorClose"
      class="main-editor"
    />
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { User, Collection, Search } from '@element-plus/icons-vue'
import { debounce } from 'lodash'
import axios from 'axios'
import NoteEditor from "./NoteEditor.vue"

const props = defineProps({
  userInfo: {
    type: Object,
    required: true
  }
})

const notes = ref([])
const userIdSearch = ref('')
const topicSearch = ref('')
const showNoteEditor = ref(false)
const currentNoteId = ref(null)
const isLoading = ref(false)

const currentUserId = computed(() => props.userInfo.id)

const fetchNotes = async (userId) => {
  if (isLoading.value) return

  isLoading.value = true
  try {
    const targetUserId = userId || currentUserId.value
    const response = await axios.get(`/backend/api/note/list/${targetUserId}/`)
    notes.value = response.data
  } catch (error) {
    console.error('获取笔记列表失败:', error)
    if (error.response && error.response.status === 404) {
      ElMessage.error('用户不存在')
    } else {
      ElMessage.error('获取笔记列表失败')
    }
  } finally {
    isLoading.value = false
  }
}

const queryTopicSuggestions = async (queryString, callback) => {
  if (queryString.length === 0) {
    callback([])
    return
  }

  try {
    const response = await axios.get(`/backend/api/note/search/topics/?q=${queryString}`)
    const suggestions = response.data.topics.map(topic => ({
      value: topic
    }))
    callback(suggestions)
  } catch (error) {
    console.error('获取话题建议失败:', error)
    callback([])
  }
}

const searchNotesByTopic = async (topic) => {
  if (isLoading.value) return

  isLoading.value = true
  try {
    const response = await axios.get(`/backend/api/note/search/notes/?q=${topic}`)
    // 修改这里：将返回的笔记数据格式化为与普通笔记列表相同的格式
    notes.value = response.data.notes.map(note => ({
      id: note.id,
      content: note.title,  // 使用返回的 title 作为 content
      topic: note.topic,
      is_public: true,      // 搜索返回的都是公开笔记
      created_at: new Date().toISOString(), // 由于API没有返回时间，使用当前时间
      user: currentUserId.value // 假设是当前用户的笔记
    }))
  } catch (error) {
    console.error('搜索笔记失败:', error)
    ElMessage.error('搜索笔记失败')
  } finally {
    isLoading.value = false
  }
}

const handleUserSearch = () => {
  if (userIdSearch.value) {
    fetchNotes(userIdSearch.value)
  } else {
    fetchNotes(currentUserId.value)
  }
}

const handleTopicSelect = (item) => {
  searchNotesByTopic(item.value)
}

const createNewNote = () => {
  if (!currentUserId.value) {
    ElMessage.error('请先登录')
    return
  }
  currentNoteId.value = null
  showNoteEditor.value = true
}

const editNote = (note) => {
  if (note.user !== currentUserId.value) {
    ElMessage.error('没有权限编辑此笔记')
    return
  }
  currentNoteId.value = note.id
  showNoteEditor.value = true
}

const viewNoteDetails = (note) => {
  currentNoteId.value = note.id
  showNoteEditor.value = true
}

const handleEditorClose = () => {
  showNoteEditor.value = false
  currentNoteId.value = null
  fetchNotes(currentUserId.value)
}

const deleteNote = async (note) => {
  if (note.user !== currentUserId.value) {
    ElMessage.error('没有权限删除此笔记')
    return
  }

  try {
    await ElMessageBox.confirm('确定要删除这篇笔记吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    await axios.delete(`/backend/api/note/delete/${note.id}/`)
    ElMessage.success('笔记删除成功')
    fetchNotes(currentUserId.value)
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除笔记失败:', error)
      ElMessage.error('删除笔记失败')
    }
  }
}

const filteredNotes = computed(() => {
  if (userIdSearch.value && userIdSearch.value !== currentUserId.value) {
    return notes.value.filter(note => note.is_public)
  }
  return notes.value
})

const formatDate = (dateString) => {
  return new Date(dateString).toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

onMounted(() => {
  if (currentUserId.value) {
    fetchNotes(currentUserId.value)
  }
})
</script>

<style scoped>
.notes-container {
  background: #fff;
  border-radius: 4px;
  padding: 20px;
}

.notes-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.title {
  font-size: 16px;
  font-weight: bold;
}

.search-container {
  display: flex;
  gap: 16px;
  margin-bottom: 20px;
  max-width: 500px;
}

.search-input-group {
  display: flex;
  gap: 8px;
  width: 280px;
}

.search-input-group .search-input {
  width: 200px;
}

.search-input-group .search-button {
  flex-shrink: 0;
}

.search-input:not(.search-input-group .search-input) {
  width: 180px;
}

.action-buttons {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  gap: 8px;
}

.edit-btn,
.delete-btn {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  height: 24px;
  padding: 0 8px;
  font-size: 12px;
}

.edit-btn {
  color: #409eff;
}

.edit-btn:hover {
  color: #66b1ff;
}

.delete-btn {
  color: #f56c6c;
}

.delete-btn:hover {
  color: #ff4949;
}

.main-editor {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #fff;
  z-index: 10;
  padding: 20px;
  overflow-y: auto;
}
</style>